<!---总览数据页面-->
<template>
  <div class="ele-body ele-body-card">
    <a-row>
      <a-col :span="12" class="block-space-right">
        <a-card title="设备信息" class="card-width">
          <a-descriptions bordered :column="1">
            <a-descriptions-item label="牛号">{{ data.cattleNo }}</a-descriptions-item>
            <a-descriptions-item label="温度计序列号">{{ data.thermNo }}</a-descriptions-item>
            <a-descriptions-item label="耳标号1">{{ data.earOne }}</a-descriptions-item>
            <a-descriptions-item label="耳标号2">{{ data.earTwo }}</a-descriptions-item>
            <a-descriptions-item label="围栏">{{ data.fence }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
      <a-col :span="12" class="block-space-right">
        <!-- 右边统计快 -->
        <a-card title="实时数据" class="card-width">
          <a-row :gutter="8">
            <a-col :span="8">
              <a-card>
                <a-statistic
                  title="呼吸速率(次/min)"
                  :value="cattleData.respirationRate"
                  :precision="0"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card>
                <a-statistic
                  title="心跳速率(次/min)"
                  :value="cattleData.heartRate"
                  :precision="0"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
            <a-col :span="8">
              <a-card>
                <a-statistic
                  title="速率状态"
                  :value="cattleData.rateStateText"
                  :precision="0"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
          </a-row>
          <a-row :gutter="8">
            <a-col :span="8">
              <a-card>
                <a-statistic
                  title="瘤胃温度(℃)"
                  :value="cattleData.bodyTemperature"
                  :precision="1"
                  suffix=""
                  class="demo-class"
                  :value-style="{ color: '#cf1322' }"
                />
              </a-card>
            </a-col>
            <a-col :span="8"/>
            <a-col :span="8"/>
          </a-row>
        </a-card>
      </a-col>
    </a-row>

    <!-- 报表统计 -->
    <a-row :gutter="16">
      <a-col :lg="24" :md="24" :sm="24" :xs="24">
        <a-card
          :bordered="false"
          title="最近4小时瘤胃温度情况"
          :body-style="{padding: '16px 6px 0 0'}">
          <template #extra>
            <a-space size="middle" class="analysis-tabs-extra">
              <a-radio-group v-model:value="chartWhere.dateType" @change="selectDataType">
                <a-radio-button :value="1">4小时</a-radio-button>
                <a-radio-button :value="2">8小时</a-radio-button>
                <a-radio-button :value="3">12小时</a-radio-button>
                <a-radio-button :value="4">1天内</a-radio-button>
                <a-radio-button :value="5">2天内</a-radio-button>
              </a-radio-group>
            </a-space>
          </template>
          <v-chart
            ref="temperatureHumidityChart"
            style="height: 362px;"
            :option="temperatureHumidityChartOption"/>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16">
      <a-col :lg="24" :md="24" :sm="24" :xs="24">
        <a-card
          :bordered="false"
          title="实时呼吸速率"
          :body-style="{padding: '16px 6px 0 0'}">
          <v-chart
            ref="respirationRateChart"
            style="height: 362px;"
            :option="respirationRateChartOption"/>
        </a-card>
      </a-col>
    </a-row>

    <a-row :gutter="16">
      <a-col :lg="24" :md="24" :sm="24" :xs="24">
        <a-card
          :bordered="false"
          title="实时心跳速率"
          :body-style="{padding: '16px 6px 0 0'}">
          <v-chart
            ref="heartRateChart"
            style="height: 362px;"
            :option="heartRateChartOption"/>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import {provide} from 'vue';
import {use} from 'echarts/core';
import {CanvasRenderer} from 'echarts/renderers';
import {LineChart, BarChart} from 'echarts/charts';
import {
  GridComponent,
  TooltipComponent,
  LegendComponent
} from 'echarts/components';
import VChart, {THEME_KEY} from 'vue-echarts';
import 'echarts-wordcloud';
import {ChartTheme} from 'ele-admin-pro';
import {CattleRealtimeDataApi} from '@/api/property/cattlemanager/CattleRealtimeDataApi';
import {CattleTemperatureDataApi} from '@/api/property/cattlemanager/CattleTemperatureDataApi';
import {CattleHeartbeatDataApi} from "@/api/property/cattlemanager/CattleHeartbeatDataApi";
import moment from 'moment'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent
]);

provide(THEME_KEY, ChartTheme);

export default {
  name: 'CattleManagerCattlehealthdataMonitor',
  components: {
    VChart,
  },
  props: {
    data: Object
  },
  data() {
    return {
      // 最近1小时温度情况
      temperatureHumidityData: [],
      heartData : [],
      cattleData: {},
      loadTimer: null, //定义一个刷新的timer
      loadDetailTimer: null,
      loadRealtimeHeartDataTimer : null,
      chartWhere: {
        "dateType": 1,
        "searchBeginTime": moment().subtract(4, 'h').format('YYYY-MM-DD HH:mm:ss'),
      }
    };
  },
  mounted() {
    this.getTemperatureHumidityData();
    this.getHeartData();
    this.getDetail();
    this.loadTimer = setInterval(this.getTemperatureHumidityData, 30000);
    this.loadDetailTimer = setInterval(this.getDetail, 30000);
    this.loadRealtimeHeartDataTimer = setInterval(this.getHeartDataFirst, 3000);
  },
  beforeUnmount() {
    clearInterval(this.loadTimer);
    clearInterval(this.loadDetailTimer);
    clearInterval(this.loadRealtimeHeartDataTimer);
  },
  computed: {
    //心跳速率
    heartRateChartOption(){
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['心跳速率'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.heartData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '心跳速率',
            type: 'line',
            showSymbol: false,
            data: this.heartData.map(d => d.heartRate)
          },
        ]
      }
    },
    //呼吸速率
    respirationRateChartOption() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['呼吸速率'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.heartData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '呼吸速率',
            type: 'line',
            showSymbol: false,
            data: this.heartData.map(d => d.respirationRate)
          },
        ]
      }
    },
    // 最近1小时温度情况折线图配置
    temperatureHumidityChartOption() {
      return {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['温度'],
          right: 20
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: this.temperatureHumidityData.map(d => d.time)
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '温度',
            type: 'line',
            smooth: true,
            symbol: 'none',
            areaStyle: {
              opacity: 0.5
            },
            data: this.temperatureHumidityData.map(d => d.temperature)
          }
        ]
      }
    }
  },
  methods: {
    getDetail() {
      let that = this;
      CattleRealtimeDataApi.detail({"cattleId": this.data.cattleId}).then(result => {
        that.cattleData = result || {};
        if (that.cattleData.rateState == 0) {
          that.cattleData.rateStateText = "无目标";
        } else if (that.cattleData.rateState == 1) {
          that.cattleData.rateStateText = "信号微弱";
        } else if (that.cattleData.rateState == 2) {
          that.cattleData.rateStateText = "呼吸正常";
        } else if (that.cattleData.rateState == 3) {
          that.cattleData.rateStateText = "异常移动";
        }
      });
    },
    selectDataType() {
      clearInterval(this.loadTimer);
      if (this.chartWhere.dateType == 1) {
        this.chartWhere.searchBeginTime = moment().subtract(4, 'h').format('YYYY-MM-DD HH:mm:ss');
      } else if (this.chartWhere.dateType == 2) {
        this.chartWhere.searchBeginTime = moment().subtract(5, 'h').format('YYYY-MM-DD HH:mm:ss');
      } else if (this.chartWhere.dateType == 3) {
        this.chartWhere.searchBeginTime = moment().subtract(12, 'h').format('YYYY-MM-DD HH:mm:ss');
      } else if (this.chartWhere.dateType == 4) {
        this.chartWhere.searchBeginTime = moment().subtract(24, 'h').format('YYYY-MM-DD HH:mm:ss');
      } else if (this.chartWhere.dateType == 5) {
        this.chartWhere.searchBeginTime = moment().subtract(48, 'h').format('YYYY-MM-DD HH:mm:ss');
      }
      clearInterval(this.loadDetailTimer);
      clearInterval(this.loadRealtimeHeartDataTimer);
      this.getTemperatureHumidityData();
      this.loadTimer = setInterval(this.getTemperatureHumidityData, 30000);
      this.getHeartData();
      this.loadRealtimeHeartDataTimer = setInterval(this.getHeartDataFirst, 3000);
    },
    getTemperatureHumidityData() {
      let params = {
        searchBeginTime: this.chartWhere.searchBeginTime,
        searchEndTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        cattleId: this.data.cattleId,
        orderBy: "asc",
        sortBy: "upload_time"
      };
      CattleTemperatureDataApi.list(params).then(list => {
        let _temperatureHumidityData = [];
        if (list && list.length > 0) {
          list.forEach(function (item) {
            let formatItem = {
              time: item.uploadTime.substr(0, 16),
              temperature: item.bodyTemperature
            };
            _temperatureHumidityData.push(formatItem);
          });
        } else {
          _temperatureHumidityData.push({
            time: moment().subtract(20, 'minute').format('YYYY-MM-DD HH:mm'),
            temperature: 0
          });
          _temperatureHumidityData.push({
            time: moment().subtract(10, 'minute').format('YYYY-MM-DD HH:mm'),
            temperature: 0
          });
          _temperatureHumidityData.push({
            time: moment().subtract(5, 'minute').format('YYYY-MM-DD HH:mm'),
            temperature: 0
          });
        }
        this.temperatureHumidityData = _temperatureHumidityData;
      });
    },
    getHeartData() {
      let params = {
        searchBeginTime: this.chartWhere.searchBeginTime,
        searchEndTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        cattleId: this.data.cattleId,
        rateStates : "1,2,3",
        orderBy : "asc",
        sortBy : "create_time"
      };
      CattleHeartbeatDataApi.list(params).then(list => {
        let _heartData = [];
        if (list && list.length > 0) {
          let split = 0;
          if (list.length > 120 && list.length < 180) {
            split = 9;
          } else if (list.length > 180 && list.length < 300) {
            split = 15;
          } else if (list.length > 300) {
            split = 35;
          }
          let i = 0;
          list.forEach(function (item) {
            let formatItem = {
              time: item.createTime.substr(0, 16),
              respirationRate: item.respirationRate,
              heartRate: item.heartRate
            };
            i++;
            if (split > 0 && i % split == 0) {
              _heartData.push(formatItem);
            }
          });
        } else {
          _heartData.push({
            time: moment().subtract(20, 'minute').format('YYYY-MM-DD HH:mm'),
            respirationRate: 0,
            heartRate: 0,
          });
          _heartData.push({
            time: moment().subtract(10, 'minute').format('YYYY-MM-DD HH:mm'),
            respirationRate: 0,
            heartRate: 0,
          });
          _heartData.push({
            time: moment().subtract(5, 'minute').format('YYYY-MM-DD HH:mm'),
            respirationRate: 0,
            heartRate: 0,
          });
        }
        this.heartData = _heartData;
      });
    },
    getHeartDataFirst() {
      let params = {
        searchBeginTime: this.chartWhere.searchBeginTime,
        searchEndTime: moment().format('YYYY-MM-DD HH:mm:ss'),
        cattleId: this.data.cattleId,
        pageNo : 1,
        pageSize : 1,
        rateStates : "1,2,3"
      };
      let that = this;
      CattleHeartbeatDataApi.findPage(params).then(list => {
        if (list && list.rows.length > 0) {
          list.rows.forEach(function (item) {
            if (that.heartData.length > 50) {
              that.heartData.shift();
            }
            let formatItem = {
              time: item.createTime.substr(0, 16),
              respirationRate: item.respirationRate,
              heartRate: item.heartRate
            };
            that.heartData.push(formatItem);
          });
        }
      });
    }
  },

  activated() {
    ['temperatureHumidityChart', 'respirationRateChart', 'heartRateChart'].forEach((name) => {
      this.$refs[name].resize();
    });
  }
};
</script>
<style scoped>
.block-space-top {
  /*上右下左*/
  padding: 10px 0 0 0;
}

.block-space-right {
  padding: 0 5px 0 0;
}

.block-space-left {
  padding: 0 0 0 5px;
}

.card-width {
  width: 100%;
}

@media screen and (max-width: 880px) {
  .analysis-tabs-extra {
    display: none;
  }
}
</style>
